<template>
  <view class="demo-container">
    <view class="demo-header">
      <view class="title">日期范围选择器</view>
      <text class="subtitle">用于选择开始和结束日期范围</text>
    </view>

    <!-- 日期选择器 -->
    <date-range-calendar
      :mode="calendarMode"
      :min-date="minDate"
      :max-date="maxDate"
      :initial-start-date="initialStartDate"
      :initial-end-date="initialEndDate"
      :allow-same-day="allowSameDay"
      :disabled-dates="disabledDates"
      :show-footer="showFooter"
      :show-header="showHeader"
      :today-date="customToday"
      :auto-select-first-day="autoSelectFirstDay"
      :marked-dates="simplifiedMarkedDates"
      :marked-dates-type="'default'"
      :multiple-indicators="true"
      :max-indicators-per-day="3"
      @date-selection-change="handleDateChange"
      @confirm="handleConfirm"
      @reset="handleReset"
      @calendar-expand="handleCalendarExpand"
      @calendar-collapse="handleCalendarCollapse"
    />

    <!-- 当前选择结果展示 -->
    <view
      class="result-section"
      v-if="calendarMode === 'single' && selectedDate"
    >
      <view class="section-title">选择结果</view>
      <view class="result-item">
        <text class="label">已选日期:</text>
        <text class="value">{{
          formatDate(selectedDate, "YYYY-MM-DD weekday")
        }}</text>
      </view>
    </view>

    <view
      class="result-section"
      v-if="calendarMode === 'range' && selectedRange.startDate"
    >
      <view class="section-title">选择结果</view>
      <view class="result-item">
        <text class="label">开始日期:</text>
        <text class="value">{{
          formatDate(selectedRange.startDate, "YYYY-MM-DD weekday")
        }}</text>
      </view>
      <view class="result-item" v-if="selectedRange.endDate">
        <text class="label">结束日期:</text>
        <text class="value">{{
          formatDate(selectedRange.endDate, "YYYY-MM-DD weekday")
        }}</text>
      </view>
      <view
        class="result-item"
        v-if="selectedRange.startDate && selectedRange.endDate"
      >
        <text class="label">总天数:</text>
        <text class="value"
          >{{
            calculateDays(selectedRange.startDate, selectedRange.endDate)
          }}
          天</text
        >
      </view>
    </view>

    <!-- 配置选项 -->
    <view class="config-section">
      <view class="section-title">配置选项</view>

      <view class="config-item">
        <text class="label">选择模式:</text>
        <view class="mode-switch">
          <view
            class="mode-btn"
            :class="{ active: calendarMode === 'single' }"
            @click="switchMode('single')"
          >
            单选模式
          </view>
          <view
            class="mode-btn"
            :class="{ active: calendarMode === 'range' }"
            @click="switchMode('range')"
          >
            范围选择
          </view>
        </view>
      </view>

      <view class="config-item" v-if="calendarMode === 'range'">
        <text class="label">允许选择同一天:</text>
        <switch
          :checked="allowSameDay"
          @change="toggleAllowSameDay"
          color="#4e6ef2"
        />
      </view>

      <view class="config-item">
        <text class="label">禁用周末:</text>
        <switch
          :checked="disableWeekends"
          @change="toggleDisableWeekends"
          color="#4e6ef2"
        />
      </view>
      <view class="config-item">
        <text class="label">显示顶部栏:</text>
        <switch
          :checked="showHeader"
          @change="toggleShowHeader"
          color="#4e6ef2"
        />
      </view>
      <view class="config-item">
        <text class="label">显示底部栏:</text>
        <switch
          :checked="showFooter"
          @change="toggleShowFooter"
          color="#4e6ef2"
        />
      </view>

      <view class="config-item">
        <text class="label">自动选择首日:</text>
        <switch
          :checked="autoSelectFirstDay"
          @change="toggleAutoSelectFirstDay"
          color="#4e6ef2"
        />
      </view>

      <view class="config-item">
        <text class="label">显示日期指示器:</text>
        <switch
          :checked="showIndicators"
          @change="toggleIndicators"
          color="#4e6ef2"
        />
      </view>

      <view class="config-item" v-if="showIndicators">
        <view class="indicator-legend">
          <view class="indicator-item">
            <view class="indicator-dot indicator-default"></view>
            <text class="indicator-text">默认</text>
          </view>
          <view class="indicator-item">
            <view class="indicator-dot indicator-primary"></view>
            <text class="indicator-text">重要</text>
          </view>
          <view class="indicator-item">
            <view class="indicator-dot indicator-secondary"></view>
            <text class="indicator-text">一般</text>
          </view>
          <view class="indicator-item">
            <view class="indicator-dot indicator-warning"></view>
            <text class="indicator-text">提醒</text>
          </view>
        </view>
        <view class="btn regenerate-btn" @click="regenerateSimplifiedMarkers"
          >重新生成</view
        >
      </view>

      <view
        class="config-item"
        v-if="showIndicators && simplifiedMarkedDates.length > 0"
      >
        <text class="indicator-dates-title">已生成的指示器日期:</text>
        <view class="indicator-dates-list">
          <view
            class="indicator-date-item"
            v-for="(item, index) in simplifiedMarkedDates"
            :key="index"
          >
            <view
              class="indicator-dot"
              :class="[`indicator-${item.type || 'default'}`]"
            ></view>
            <text class="indicator-date-text"
              >{{ item.date }} {{ item.date }}</text
            >
          </view>
        </view>
      </view>

      <view class="config-item">
        <text class="label">今天日期:</text>
        <text class="value">{{ formatDate(customToday) }}</text>
        <view class="btn set-today-btn" @click="setTodayToToday">重置</view>
        <view class="btn set-custom-btn" @click="setCustomToday">修改</view>
      </view>

      <view class="config-item" v-if="calendarMode === 'range'">
        <text class="label">最大选择范围:</text>
        <picker
          mode="selector"
          :range="maxRangeOptions"
          @change="changeMaxRange"
          class="picker"
        >
          <view class="picker-value">{{ maxRangeOptions[maxRangeIndex] }}</view>
        </picker>
      </view>
    </view>
  </view>
</template>

<script>
import DateRangeCalendar from "@/components/common/DateRangeCalendar.vue";

export default {
  name: "CalendarDemo",
  components: {
    DateRangeCalendar,
  },
  data() {
    return {
      // 选择器配置
      minDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
      maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
      initialStartDate: null,
      initialEndDate: null,
      allowSameDay: false,
      disabledDates: [],
      disableWeekends: false,
      showHeader: true,
      showFooter: true,
      autoSelectFirstDay: false,

      // 日期指示器配置
      showIndicators: false,

      // 指示器配置
      simplifiedMarkedDates: [],

      // 选择结果 - 范围选择模式
      selectedRange: {
        startDate: null,
        endDate: null,
      },

      // 选择结果 - 单选模式
      selectedDate: null,

      // 最大范围选项
      maxRangeOptions: ["无限制", "30天", "60天", "90天", "180天", "365天"],
      maxRangeIndex: 0,
      maxRangeDays: null,

      // 选择模式
      calendarMode: "single",

      // 自定义今天日期
      customToday: new Date(),
    };
  },
  methods: {
    // 格式化日期
    formatDate(date, format = "YYYY-MM-DD") {
      if (!date) return "";

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const weekday = weekdays[date.getDay()];

      // 根据格式参数返回不同格式的日期
      let result = format;

      // 替换年月日
      result = result.replace("YYYY", year);
      result = result.replace("MM", month);
      result = result.replace("DD", day);

      // 替换星期
      result = result.replace("weekday", weekday);

      return result;
    },

    // 计算两个日期之间的天数
    calculateDays(startDate, endDate) {
      if (!startDate || !endDate) return 0;
      const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
      const start = new Date(startDate.setHours(0, 0, 0, 0));
      const end = new Date(endDate.setHours(0, 0, 0, 0));
      return Math.round(Math.abs((end - start) / oneDay)) + 1; // 包括起始日
    },

    // 处理日期选择变更
    handleDateChange(data) {
      console.log("日期选择变更:", data);

      // 单选模式
      if (this.calendarMode === "single") {
        this.selectedDate = data.date;
        return;
      }

      // 范围选择模式
      this.selectedRange = data;

      // 检查最大范围限制
      if (data.startDate && data.endDate && this.maxRangeDays) {
        const days = this.calculateDays(data.startDate, data.endDate);
        if (days > this.maxRangeDays) {
          uni.showToast({
            title: `最多只能选择${this.maxRangeDays}天`,
            icon: "none",
          });
        }
      }
    },

    // 处理确认选择
    handleConfirm(data) {
      console.log("确认选择:", data);

      // 单选模式
      if (this.calendarMode === "single") {
        this.selectedDate = data.date;
        uni.showToast({
          title: "日期选择已确认",
          icon: "success",
        });
        return;
      }

      // 范围选择模式
      // 如果有最大天数限制，验证选择是否超出限制
      if (this.maxRangeDays) {
        const days = this.calculateDays(data.startDate, data.endDate);
        if (days > this.maxRangeDays) {
          uni.showToast({
            title: `最多只能选择${this.maxRangeDays}天`,
            icon: "none",
          });
          return;
        }
      }

      this.selectedRange = {
        startDate: data.startDate,
        endDate: data.endDate,
      };

      uni.showToast({
        title: "日期选择已确认",
        icon: "success",
      });
    },

    // 处理重置
    handleReset() {
      console.log("重置选择");
      if (this.calendarMode === "single") {
        this.selectedDate = null;
      } else {
        this.selectedRange = {
          startDate: null,
          endDate: null,
        };
      }

      // 同时清空指示器数据
      this.simplifiedMarkedDates = [];
      this.showIndicators = false;
    },

    // 切换是否允许选择同一天
    toggleAllowSameDay(e) {
      this.allowSameDay = e.detail.value;
    },

    // 切换是否禁用周末
    toggleDisableWeekends(e) {
      this.disableWeekends = e.detail.value;
      this.updateDisabledDates();
    },

    // 更新禁用日期
    updateDisabledDates() {
      if (this.disableWeekends) {
        // 禁用未来一年内的所有周末
        const disabledDates = [];
        const today = new Date();
        const oneYearLater = new Date(
          today.getFullYear() + 1,
          today.getMonth(),
          today.getDate()
        );

        for (
          let date = new Date(today);
          date <= oneYearLater;
          date.setDate(date.getDate() + 1)
        ) {
          // 0是周日，6是周六
          if (date.getDay() === 0 || date.getDay() === 6) {
            disabledDates.push(new Date(date));
          }
        }

        this.disabledDates = disabledDates;
      } else {
        this.disabledDates = [];
      }
    },

    // 切换指示器显示
    toggleIndicators(e) {
      this.showIndicators = e.detail.value;

      if (this.showIndicators) {
        // 打开指示器时，自动生成数据
        this.generateSimplifiedMarkers();
      } else {
        // 关闭指示器时，清空数据
        this.simplifiedMarkedDates = [];
      }
    },

    // 生成指示器数据
    generateSimplifiedMarkers() {
      // 清空现有数据
      this.simplifiedMarkedDates = [];

      if (!this.showIndicators) return;

      // 生成数据
      const today = new Date();
      const markedDates = [];

      // 生成4天的随机日期
      for (let i = 0; i < 4; i++) {
        const randomDays = Math.floor(Math.random() * 20);
        const date = new Date(today);
        date.setDate(date.getDate() + randomDays);

        // 为每天添加2-3个不同类型的标记
        const types = ["default", "primary", "secondary", "warning"];
        const numMarkers = Math.floor(Math.random() * 2) + 2; // 2-3个

        for (let j = 0; j < numMarkers; j++) {
          markedDates.push({
            date: this.formatDate(date), // 使用格式化的日期字符串
            type: types[j % types.length],
          });
        }
      }

      // 排序显示，便于查看
      markedDates.sort((a, b) => a.date.localeCompare(b.date));

      this.simplifiedMarkedDates = markedDates;
      // console.log('已生成多类型指示器:', markedDates);

      // 显示提示
      uni.showToast({
        title: "已生成多类型指示器",
        icon: "none",
        duration: 1500,
      });
    },

    // 切换多指示器模式
    switchMode(mode) {
      this.calendarMode = mode;
      // 切换模式时重置选择
      this.handleReset();
    },
    // 切换是否显示顶部栏
    toggleShowHeader(e) {
      this.showHeader = e.detail.value;
    },
    // 切换是否显示底部栏
    toggleShowFooter(e) {
      this.showFooter = e.detail.value;
    },

    // 切换是否自动选择首日
    toggleAutoSelectFirstDay(e) {
      this.autoSelectFirstDay = e.detail.value;
    },

    // 处理日历展开
    handleCalendarExpand() {
      console.log("日历展开");
    },

    // 处理日历收缩
    handleCalendarCollapse() {
      console.log("日历收缩");
    },

    // 重置今天日期为今天
    setTodayToToday() {
      this.customToday = new Date();
    },

    // 设置一个自定义的"今天"日期
    setCustomToday() {
      // 显示日期选择器
      uni.showActionSheet({
        itemList: ["选择明天", "选择一周前", "选择一个月前", "选择自定义日期"],
        success: (res) => {
          const now = new Date();
          switch (res.tapIndex) {
            case 0: // 明天
              now.setDate(now.getDate() + 1);
              this.customToday = new Date(now);
              console.log(
                "选择明天为today:",
                this.formatDate(this.customToday)
              );
              break;
            case 1: // 一周前
              now.setDate(now.getDate() - 7);
              this.customToday = new Date(now);
              console.log(
                "选择一周前为today:",
                this.formatDate(this.customToday)
              );
              break;
            case 2: // 一个月前
              now.setMonth(now.getMonth() - 1);
              this.customToday = new Date(now);
              console.log(
                "选择一个月前为today:",
                this.formatDate(this.customToday)
              );
              break;
            case 3: // 自定义日期 - 使用日期选择器
              uni.showToast({
                title: "请使用系统日期选择器选择日期",
                icon: "none",
                duration: 2000,
              });
              break;
          }

          // 确保Vue响应式系统捕获到customToday的变化
          this.customToday = new Date(this.customToday);

          uni.showToast({
            title: `已设置今天为: ${this.formatDate(this.customToday)}`,
            icon: "none",
            duration: 1500,
          });
        },
      });
    },

    // 重新生成指示器标记
    regenerateSimplifiedMarkers() {
      this.generateSimplifiedMarkers();
      uni.showToast({
        title: "已重新生成指示器",
        icon: "none",
      });
    },

    // 更改最大选择范围
    changeMaxRange(e) {
      this.maxRangeIndex = e.detail.value;
      const option = this.maxRangeOptions[this.maxRangeIndex];

      // 设置最大天数限制
      if (option === "无限制") {
        this.maxRangeDays = null;
      } else {
        this.maxRangeDays = parseInt(option);
      }
    },
    // 检查日期是否可选
    isAvailableDayByDate(date) {
      if (!date) return false;

      // 确保传入的是有效的日期对象
      const validDate = dateHelpers.handleMiniProgramDate(date);
      if (!validDate) return false;

      // 获取日期的时间戳用于比较
      const timestamp = validDate.getTime();

      // 1. 检查是否在最小日期之前
      if (this.minTimestamp && timestamp < this.minTimestamp) {
        return false;
      }

      // 2. 检查是否在最大日期之后
      if (this.maxTimestamp && timestamp > this.maxTimestamp) {
        return false;
      }

      // 3. 检查是否在禁用日期列表中
      if (this.disabledDates && this.disabledDates.length > 0) {
        const formattedDate = this.formatDate(validDate);
        if (this.disabledDates.includes(formattedDate)) {
          return false;
        }
      }

      return true;
    },
  },
};
</script>

<style scoped>
.demo-container {
  padding: 30rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.demo-header {
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #999;
}

.result-section,
.config-section {
  margin-top: 40rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.result-item,
.config-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
  padding: 10rpx 0;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  color: #333;
  font-size: 28rpx;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 10rpx;
  margin-left: 10rpx;
}

.picker {
  flex: 1;
  text-align: right;
}

.picker-value {
  font-size: 28rpx;
  color: #4e6ef2;
}

.mode-switch {
  display: flex;
  background-color: #f0f0f0;
  border-radius: 12rpx;
  overflow: hidden;
  width: 320rpx;
}

.mode-btn {
  flex: 1;
  text-align: center;
  padding: 12rpx 20rpx;
  font-size: 28rpx;
  transition: all 0.3s;
}

.mode-btn.active {
  background-color: #4e6ef2;
  color: #fff;
}

.btn {
  padding: 10rpx 20rpx;
  background-color: #4e6ef2;
  color: #fff;
  border-radius: 12rpx;
  font-size: 28rpx;
  margin-left: 10rpx;
  height: 70rpx;
}

.set-today-btn {
  background-color: #28a745;
}

.set-custom-btn {
  background-color: #6c757d;
}

.indicator-legend {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 10rpx;
}

.indicator-item {
  display: flex;
  align-items: center;
}

.indicator-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 8rpx;
}

.indicator-text {
  font-size: 24rpx;
  color: #666;
}

.indicator-default {
  background-color: #0366d6;
}

.indicator-primary {
  background-color: #e53e3e;
}

.indicator-secondary {
  background-color: #38a169;
}

.indicator-warning {
  background-color: #ed8936;
}

.indicator-dates-title {
  font-size: 28rpx;
  color: #666;
  width: 100%;
  margin-bottom: 10rpx;
}

.indicator-dates-list {
  width: 100%;
  margin-bottom: 10rpx;
}

.indicator-date-item {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
  background-color: #f5f5f5;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.indicator-date-text {
  font-size: 26rpx;
  color: #333;
  margin-left: 10rpx;
}

.regenerate-btn {
  margin-top: 10rpx;
  width: 100%;
  text-align: center;
}
</style> 